import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_component_core/utils/base_component_utils.dart';

class BaseSelectYearAndMonth extends StatefulWidget {
  final int year;
  final int month;
  final Function(int year, int month) selected;

  const BaseSelectYearAndMonth({Key key, @required this.year, @required this.month, @required this.selected}) : super(key: key);

  @override
  _BaseSelectYearAndMonthState createState() => _BaseSelectYearAndMonthState();
}

class _BaseSelectYearAndMonthState extends State<BaseSelectYearAndMonth> {
  /// 滚动列表item的豪赌
  static final double itemHeight = 48;

  /// 系统颜色 黑 Color(0xff333333) 白：Color(0xffffffff) 黑白主题选中颜色为Color(0xFFFF004F)
  Color get systemColor => Theme.of(context).primaryColor == Colors.white ? Color(0xFF333333) : Theme.of(context).primaryColor;

  /// 当前选择的年份
  int currSelectedYear;

  /// 当前选择的月份
  int currSelectedMonth;

  /// 当前日期
  DateTime get nowTime => DateTime.now();

  /// 年的索引
  int yearIndex;

  /// 月的索引
  int monthIndex;

  /// 控制器
  FixedExtentScrollController yearScrollController;
  FixedExtentScrollController monthScrollController;

  // 年数组
  List<int> yearList = [];

  // 月数组
  List<int> monthList = [];

  @override
  void initState() {
    super.initState();
    if (widget.year != null) currSelectedYear = widget.year;
    if (widget.month != null) currSelectedMonth = widget.month;
    if (currSelectedYear == null) currSelectedYear = nowTime.year;
    if (currSelectedMonth == null) currSelectedMonth = nowTime.month;
    setupData();
    initSelectedIndex();
  }

  @override
  void dispose() {
    yearScrollController.dispose();
    monthScrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(left: 16, right: 16, bottom: 8),
      child: Column(
        children: [
          buildHead(),
          BaseComponentUtils.buildHorizontalDivider(),
          Expanded(child: buildYearAndMonthPickerView()),
        ],
      ),
    );
  }

  Widget buildHead() {
    return Container(
      color: Colors.white,
      margin: EdgeInsets.symmetric(vertical: 4),
      height: 40,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          InkWell(onTap: onCancelEvent, child: Text('取消', style: Theme.of(context).textTheme.bodyText2.copyWith(fontSize: 14))),
          Expanded(child: SizedBox()),
          InkWell(onTap: onConfirmEvent, child: Text('确认', style: Theme.of(context).textTheme.bodyText2.copyWith(fontSize: 14, color: systemColor, fontWeight: FontWeight.bold))),
        ],
      ),
    );
  }

  Widget buildYearAndMonthPickerView() {
    return Container(
      child: Row(
        children: <Widget>[
          Expanded(child: buildYearPickerView()),
          Expanded(child: buildMonthPickerView()),
        ],
      ),
    );
  }

  Widget buildYearPickerView() {
    return Container(
      child: CupertinoPicker(
        itemExtent: itemHeight,
        scrollController: yearScrollController,
        children: buildYearWidget(),
        looping: false,
        selectionOverlay: Container(
          width: double.infinity,
          height: itemHeight,
          decoration: BoxDecoration(border: Border(top: BorderSide(color: Color(0xFFEFEFEF)), bottom: BorderSide(color: Color(0xFFEFEFEF)))),
        ),
        onSelectedItemChanged: (index) {
          yearIndex = index;
          currSelectedYear = yearList[yearIndex];
          if (currSelectedYear == nowTime.year && monthIndex > nowTime.month) {
            monthIndex = nowTime.month - 1;
            monthScrollController.jumpToItem(monthIndex);
          }

          if (currSelectedYear == nowTime.year - 1) {
            // 当前月进度
            double monthOffset = monthScrollController.offset;
            // 由于切换后月份不更新，唯有滚动一点点距离才能刷新，所有有这行代码
            monthScrollController.jumpTo(monthOffset == 0.0 ? 0.01 : monthOffset - 0.01);
          }
          setState(() {});
        },
      ),
    );
  }

  Widget buildMonthPickerView() {
    return Container(
      child: CupertinoPicker(
        itemExtent: itemHeight,
        scrollController: monthScrollController,
        children: buildMonthWidget(),
        looping: false,
        selectionOverlay: Container(
          width: double.infinity,
          height: itemHeight,
          decoration: BoxDecoration(border: Border(top: BorderSide(color: Color(0xFFEFEFEF)), bottom: BorderSide(color: Color(0xFFEFEFEF)))),
        ),
        onSelectedItemChanged: (index) {
          monthIndex = index;
          currSelectedMonth = monthList[monthIndex];
          setState(() {});
        },
      ),
    );
  }

  List<Widget> buildYearWidget() {
    List<Widget> yearListWidget = []; //先建一个数组用于存放循环生成的widget
    for (var item in yearList) {
      yearListWidget.add(Center(child: Text('$item年', style: TextStyle(color: Colors.black87, fontSize: 16), maxLines: 1)));
    }

    return yearListWidget;
  }

  ///月Widget
  List<Widget> buildMonthWidget() {
    List<Widget> monthListWidget = []; //先建一个数组用于存放循环生成的widget
    //已有月份
    List<int> alreadyMonthList = currSelectedYear == nowTime.year ? List.generate(nowTime.month, (index) => index + 1) : monthList;
    for (var item in alreadyMonthList) {
      monthListWidget.add(Center(child: Text('$item月', style: TextStyle(color: Colors.black87, fontSize: 16), maxLines: 1)));
    }

    return monthListWidget;
  }

  /// 取消
  void onCancelEvent() {
    BaseRouterUtil.getInstance().pop();
  }

  /// 确认事件
  void onConfirmEvent() {
    widget.selected(currSelectedYear, currSelectedMonth);
    BaseRouterUtil.getInstance().pop();
  }

  ///初始化数据
  void setupData() {
    for (int i = 1970; i <= DateTime.now().year; i++) {
      yearList.add(i);
    }

    for (int i = 1; i <= 12; i++) {
      monthList.add(i);
    }
  }

  ///初始化时间索引
  void initSelectedIndex() {
    final List uniqueYearList = Set.from(yearList).toList();
    final List uniqueMonthList = Set.from(monthList).toList();

    ///获取索引
    if (currSelectedYear != null && currSelectedMonth != null) {
      setState(() {
        yearIndex = uniqueYearList.indexOf(currSelectedYear);
        monthIndex = uniqueMonthList.indexOf(currSelectedMonth);
      });
    } else {
      ///没有传选中日期默认当前系统时间
      String year = DateTime.now().year.toString();
      String month = DateTime.now().month.toString();

      setState(() {
        yearIndex = uniqueYearList.indexOf(year);
        monthIndex = uniqueYearList.indexOf(month);
      });
    }

    yearScrollController = FixedExtentScrollController(initialItem: yearIndex);
    monthScrollController = FixedExtentScrollController(initialItem: monthIndex);
  }
}
